/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/count-univalue-subtrees
   @Language: C++
   @Datetime: 19-05-15 16:46
   */

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
	pair<int,int> postorder(TreeNode *root, int &count){
		if(root==NULL) return {-1,0};
		auto left=postorder(root->left,count);
		auto right=postorder(root->right,count);
		if(left.first==-1 && right.first==-1){
			++count;
			return {1,root->val};
		}
		if(left.first==-1 && right.first!=-1 && right.second==root->val){
			++count;
			return {1,root->val};
		}
		if(right.first==-1 && left.first!=-1 && left.second==root->val){
			++count;
			return {1,root->val};
		}
		if(left.first>0 && right.first>0 && left.second==right.second && left.second==root->val){
			++count;
			return {1,root->val};
		}
		return {-2,0};
	}
public:
	/**
	 * @param root: the given tree
	 * @return: the number of uni-value subtrees.
	 */
	int countUnivalSubtrees(TreeNode * root) {
		// write your code here
		int count=0;
		postorder(root,count);
		return count;
	}
};
